package cn.wizzer.app.web.modules.controllers.platform.bus.reports;

import cn.wizzer.app.bus.modules.models.YJbxx;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipment;
import cn.wizzer.app.bus.modules.services.BusEquipmentService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.dao.Sqls;
import org.nutz.integration.json4excel.J4E;
import org.nutz.integration.json4excel.J4EColumn;
import org.nutz.integration.json4excel.J4EConf;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tcjinxiu.com
 * @time 2024-04-11 10:19:44
 *
 */
@IocBean
@At("/platform/bus/reports/equipment")
public class EquipmentController {
private static final Log log = Logs.get();
	@Inject
	BusEquipmentService busEquipmentService;
	@Inject
	private SysDictService sysDictService;
	@Inject
	private SysUnitService sysUnitService;
	@Inject
	private SysUserService sysUserService;

	@At("")
	@Ok("beetl:/platform/bus/reports/equipment/index.html")
	@RequiresAuthentication
	public void index(HttpServletRequest req) {
		req.setAttribute("statusMap", JSONObject.fromObject(sysDictService.getCodeMap("equipmentStatus")));
		req.setAttribute("statusOptions", JSONArray.fromObject(sysDictService.dictCodeTree("equipmentStatus")));
		req.setAttribute("calculateMap", JSONObject.fromObject(sysDictService.getCodeMap("calculate")));
		req.setAttribute("calculateCycleTypeMap", JSONObject.fromObject(sysDictService.getCodeMap("calculateCycleType")));

		List<NutMap> listSelect = new ArrayList<>();
		//基本信息
		listSelect.add(NutMap.NEW().addv("key", "model").addv("label", "规格型号").addv("condition","like").addv("id", "1"));
		listSelect.add(NutMap.NEW().addv("key", "detectionRange").addv("label", "检测范围").addv("condition","like").addv("id", "2"));
		listSelect.add(NutMap.NEW().addv("key", "accuracy").addv("label", "精度要求").addv("condition","like").addv("id", "3"));
		listSelect.add(NutMap.NEW().addv("key", "factoryCode").addv("label", "出厂编号").addv("condition","like").addv("id", "4"));
		listSelect.add(NutMap.NEW().addv("key", "company").addv("label", "制造厂商").addv("condition","like").addv("id", "5"));
		listSelect.add(NutMap.NEW().addv("key", "purchaseDate").addv("label", "购置日期").addv("condition","date").addv("id", "6"));
		listSelect.add(NutMap.NEW().addv("key", "calculate").addv("label", "溯源方式").addv("condition","drop").addv("id", "7").addv("options",JSONArray.fromObject(sysDictService.dictCodeTree("calculate"))));
		listSelect.add(NutMap.NEW().addv("key", "calculateUnit").addv("label", "溯源单位").addv("condition","like").addv("id", "8"));
		listSelect.add(NutMap.NEW().addv("key", "calculateDate").addv("label", "下次溯源日期").addv("condition","date").addv("id", "9"));
		listSelect.add(NutMap.NEW().addv("key", "depositAdress").addv("label", "存放地点").addv("condition","like").addv("id", "10"));
		listSelect.add(NutMap.NEW().addv("key", "managerBy").addv("label", "设备管理人").addv("condition","drop").addv("id", "11").addv("options",JSONArray.fromObject(sysUserService.getUserS(""))));

		List<String> roleUnits = StringUtil.dataScopeUserCnd();
		List<NutMap> units = sysUnitService.getJybmTree();
		List<NutMap> newUnits = new ArrayList<>();
		if(roleUnits!=null&& roleUnits.size()>0) {
			for (NutMap unit : units) {
				String id = unit.get("value").toString();
				if (roleUnits.contains(id)) {
					newUnits.add(unit);
				}
			}
		}else{
			newUnits = units;
		}
		listSelect.add(NutMap.NEW().addv("key", "applyDept").addv("label", "使用部门").addv("condition","drop").addv("id", "12").addv("options",JSONArray.fromObject(newUnits)));
		listSelect.add(NutMap.NEW().addv("key", "classification").addv("label", "分类情况").addv("condition","like").addv("id", "13"));
		List<NutMap> treeList = new ArrayList<>();
		NutMap map = NutMap.NEW().addv("value", "0").addv("label", "是");
		treeList.add(map);
		NutMap map1 = NutMap.NEW().addv("value", "1").addv("label", "否");
		treeList.add(map1);
		listSelect.add(NutMap.NEW().addv("key", "importedFlag").addv("label", "是否进口设备").addv("condition","drop").addv("id", "14").addv("options",JSONArray.fromObject(treeList)));
		listSelect.add(NutMap.NEW().addv("key", "supplyPhone").addv("label", "供货商联系电话").addv("condition","like").addv("id", "15"));

		req.setAttribute("listSelect", JSONArray.fromObject(listSelect));
	}



	@At
	@Ok("json:full")
	@RequiresAuthentication
	/*@RequiresPermissions("equipment.index.data")*///不要权限，因为其它功能需要读取
	public Object data(@Param("code") String code, @Param("name") String name,@Param("status") String status,@Param("listSelect") String listSelect,
					   @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize
			, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
		try {
			String sql = " select e.*,ur.username as managerName,ut.name as applyName " +
					" from bus_equipment e  " +
					" left join sys_user ur on ur.id=e.managerBy " +
					" left join sys_unit ut on ut.id = e.applyDept where e.delFlag=0 "+StringUtil.dataScopeReportJyksBh("e","applyDept");
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(status)){
				sql+= " and  e.status = '"+status+"' ";
			}
			List<JSONObject> list = JSONArray.fromObject(listSelect);
			if(list.size()>0){
				for(JSONObject object :list){
					if(object.get("condition").equals("like")){
						sql+= " and e."+object.get("key")+" like '%"+object.get("value")+"%' ";
					}
					if(object.get("condition").equals("drop")){
						String values = object.get("value").toString().replace("[\"","").replace("\"]","").replace("[]","");
						if(StringUtils.isNotBlank(values)){
							sql+= " and e."+object.get("key")+" = '"+values+"' ";
						}
					}
					if(object.get("condition").equals("number")){
						sql+= " and e."+object.get("key")+" = '"+object.get("value")+"' ";
					}
					if(object.get("condition").equals("date")){
						if(object.get("startDate")!=null && StringUtils.isNotBlank(object.get("startDate").toString())){
							sql+= " and e."+object.get("key")+" >= '"+object.get("startDate")+"' ";
						}
						if(object.get("endDate")!=null && StringUtils.isNotBlank(object.get("endDate").toString())){
							sql+= " and e."+object.get("key")+" <= '"+object.get("endDate")+"' ";
						}
					}
				}
			}
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by e."+pageOrderName+" asc,e.code asc ";
				} else {
					sql+= " order by e."+pageOrderName+" desc,e.code asc ";
				}
			}else{
				sql+= " order by e.code asc ";
			}
			return Result.success().addData(busEquipmentService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}


	@At("/detail/?")
	@Ok("json")
	public Object detail(String id) {
		try {
			return Result.success("system.success").addData(busEquipmentService.fetch(id));
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At
	@Ok("void")
	public void export(@Param("code") String code, @Param("name") String name,@Param("status") String status,@Param("listSelect") String listSelect
			, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, HttpServletResponse response) {
		try {
			String sql = " select e.*,ur.username as managerName,ut.name as applyName " +
					" from bus_equipment e  " +
					" left join sys_user ur on ur.id=e.managerBy " +
					" left join sys_unit ut on ut.id = e.applyDept where e.delFlag=0 "+StringUtil.dataScopeReportJyksBh("e","applyDept");
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(status)){
				sql+= " and  e.status = '"+status+"' ";
			}
			List<JSONObject> list = JSONArray.fromObject(listSelect);
			if(list.size()>0){
				for(JSONObject object :list){
					if(object.get("condition").equals("like")){
						sql+= " and e."+object.get("key")+" like '%"+object.get("value")+"%' ";
					}
					if(object.get("condition").equals("drop")){
						String values = object.get("value").toString().replace("[\"","").replace("\"]","").replace("[]","");
						if(StringUtils.isNotBlank(values)){
							sql+= " and e."+object.get("key")+" = '"+values+"' ";
						}
					}
					if(object.get("condition").equals("number")){
						sql+= " and e."+object.get("key")+" = '"+object.get("value")+"' ";
					}
					if(object.get("condition").equals("date")){
						if(object.get("startDate")!=null && StringUtils.isNotBlank(object.get("startDate").toString())){
							sql+= " and e."+object.get("key")+" >= '"+object.get("startDate")+"' ";
						}
						if(object.get("endDate")!=null && StringUtils.isNotBlank(object.get("endDate").toString())){
							sql+= " and e."+object.get("key")+" <= '"+object.get("endDate")+"' ";
						}
					}
				}
			}
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by e."+pageOrderName+" asc,e.code asc ";
				} else {
					sql+= " order by e."+pageOrderName+" desc,e.code asc ";
				}
			}else{
				sql+= " order by e.code asc ";
			}

			List<BusEquipment> listObj = busEquipmentService.listEntity(Sqls.create(sql));


			Map statusMap = sysDictService.getCodeMap("equipmentStatus");
			Map calculateMa=sysDictService.getCodeMap("calculate");
			Map calculateCycleTypeMap=sysDictService.getCodeMap("calculateCycleType");
			listObj.stream().map(obj -> {
				if(StringUtils.isNotBlank(obj.getStatus())){
					obj.setStatus(StringUtil.getDict(obj.getStatus(),statusMap));
				}
				if(StringUtils.isNotBlank(obj.getCalculate())){
					obj.setCalculate(StringUtil.getDict(obj.getCalculate(),calculateMa));
				}
				if(StringUtils.isNotBlank(obj.getCalculateCycleType())){
					obj.setCalculateCycleType(StringUtil.getDict(obj.getCalculateCycleType(),calculateCycleTypeMap));
				}
				if(StringUtils.isNotBlank(obj.getImportedFlag())){
					if(obj.getImportedFlag().equals("0")){
						obj.setImportedFlag("是");
					}else{
						obj.setImportedFlag("否");
					}
				}
				obj.setManagerBy(obj.getManagerName());
				obj.setApplyDept(obj.getApplyName());
				return obj;
			}).collect(Collectors.toList());

			J4EConf j4eConf = J4EConf.from(BusEquipment.class);
			List<J4EColumn> jcols = j4eConf.getColumns();
			for (J4EColumn j4eColumn : jcols) {
				if ("opBy".equals(j4eColumn.getFieldName()) || "opAt".equals(j4eColumn.getFieldName()) || "delFlag".equals(j4eColumn.getFieldName())) {
					j4eColumn.setIgnore(true);
				}
			}
			j4eConf.setSheetName(j4eConf.getSheetName()+ DateUtil.getDate());
			OutputStream out = response.getOutputStream();
			response.setHeader("content-type", "application/shlnd.ms-excel;charset=utf-8");
			response.setHeader("content-disposition", "attachment; filename=" + new String(j4eConf.getSheetName().getBytes(), "ISO-8859-1") + ".xls");
			J4E.toExcel(out, listObj, j4eConf);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
	}

}
